/*
 * Copyright 2022 Nightingale Team
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
import React, { useEffect } from 'react';
import { Form, Select, Row, Col, Switch, Radio, Button, Mentions, Space, Tooltip, Input } from 'antd';
import { DeleteOutlined, InfoCircleOutlined } from '@ant-design/icons';
import _ from 'lodash';
import { useTranslation, Trans } from 'react-i18next';
import { Panel } from '../../Components/Collapse';
import { calcsOptions } from '../../config';
import { useGlobalState } from '../../../globalState';

export default function GraphStyles({ chartForm, variableConfigWithOptions }) {
  const { t, i18n } = useTranslation('dashboard');
  const namePrefix = ['custom'];
  const [tableFields, setTableFields] = useGlobalState('tableFields');
  const [tableRefIds, setTableRefIds] = useGlobalState('tableRefIds');
  const calc = Form.useWatch([...namePrefix, 'calc']);

  useEffect(() => {
    return () => {
      setTableFields([]);
      setTableRefIds([]);
    };
  }, []);

  return (
    <Panel header={t('panel.custom.title')} data-oid='k_k:nq2'>
      <>
        <Row gutter={10} data-oid='e8oi1qz'>
          <Col span={12} data-oid='k:ayh8e'>
            <Form.Item label={t('panel.custom.table.showHeader')} name={[...namePrefix, 'showHeader']} valuePropName='checked' data-oid='yn9l:j2'>
              <Switch size='small' data-oid='a7fht3u' />
            </Form.Item>
          </Col>
          <Col span={12} data-oid='swv-mtc'>
            <Form.Item label={t('panel.custom.colorMode')} name={[...namePrefix, 'colorMode']} tooltip={t('panel.custom.table.colorMode_tip')} data-oid='b5caam9'>
              <Radio.Group buttonStyle='solid' data-oid='f_45jmp'>
                <Radio.Button value='value' data-oid='611d7pc'>
                  {t('panel.custom.value')}
                </Radio.Button>
                <Radio.Button value='background' data-oid='p5afcxp'>
                  {t('panel.custom.background')}
                </Radio.Button>
              </Radio.Group>
            </Form.Item>
          </Col>
          <Col span={12} data-oid='h3t0dyw'>
            <Form.Item label={t('panel.custom.table.nowrap')} name={[...namePrefix, 'nowrap']} valuePropName='checked' data-oid='fo-nvzd'>
              <Switch size='small' data-oid='88-84np' />
            </Form.Item>
          </Col>
          <Col span={12} data-oid='f:j.t4i'>
            <Form.Item
              label={t('panel.custom.table.tableLayout.label')}
              name={[...namePrefix, 'tableLayout']}
              tooltip={t('panel.custom.table.tableLayout.label_tip')}
              data-oid='yn1eo:6'
            >
              <Select
                options={[
                  {
                    label: t('panel.custom.table.tableLayout.fixed'),
                    value: 'fixed',
                  },
                  {
                    label: t('panel.custom.table.tableLayout.auto'),
                    value: 'auto',
                  },
                ]}
                data-oid='_baf:ph'
              />
            </Form.Item>
          </Col>
        </Row>
        <Form.Item label={t('panel.custom.calc')} name={[...namePrefix, 'calc']} tooltip={t('panel.custom.calc_tip')} data-oid='k8d8fae'>
          <Select data-oid='srg9v7i'>
            {_.map(
              {
                ...calcsOptions,
                origin: 'origin',
              },
              (item, key) => {
                return (
                  <Select.Option key={key} value={key} data-oid='nalh20j'>
                    {t(`calcs.${key}`)}
                  </Select.Option>
                );
              },
            )}
          </Select>
        </Form.Item>
        <Row gutter={10} data-oid='brehpoc'>
          <Col span={12} data-oid='t:g53ie'>
            <Form.Item label={t('panel.custom.table.displayMode')} name={[...namePrefix, 'displayMode']} data-oid=':hef0be'>
              <Select
                onChange={(val) => {
                  if (val === 'labelsOfSeriesToRows') {
                    chartForm.setFieldsValue({ custom: { columns: [] } });
                  } else if (val === 'labelValuesToRows') {
                    chartForm.setFieldsValue({ custom: { aggrDimension: [] } });
                  }
                }}
                data-oid='v3xme90'
              >
                <Select.Option value='seriesToRows' data-oid='_nm.kf8'>
                  {t('panel.custom.table.seriesToRows')}
                </Select.Option>
                <Select.Option value='labelsOfSeriesToRows' data-oid='u18wyit'>
                  {t('panel.custom.table.labelsOfSeriesToRows')}
                </Select.Option>
                <Select.Option value='labelValuesToRows' data-oid='tc9d362'>
                  {t('panel.custom.table.labelValuesToRows')}
                </Select.Option>
              </Select>
            </Form.Item>
          </Col>
          <Form.Item
            noStyle
            shouldUpdate={(prevValues, curValues) => _.get(prevValues, [...namePrefix, 'displayMode']) !== _.get(curValues, [...namePrefix, 'displayMode'])}
            data-oid='vge72m2'
          >
            {({ getFieldValue }) => {
              if (getFieldValue([...namePrefix, 'displayMode']) === 'labelsOfSeriesToRows') {
                return (
                  <Col span={12} data-oid='v0g_hxg'>
                    <Form.Item label={t('panel.custom.table.columns')} name={[...namePrefix, 'columns']} data-oid='3idveyg'>
                      <Select mode='multiple' placeholder='' data-oid='ludpe.x'>
                        {_.map(_.concat(calc === 'origin' ? '__time__' : [], tableFields, 'value'), (item) => {
                          return (
                            <Select.Option key={item} value={item} data-oid='orbconw'>
                              {item}
                            </Select.Option>
                          );
                        })}
                      </Select>
                    </Form.Item>
                  </Col>
                );
              }
              if (getFieldValue([...namePrefix, 'displayMode']) === 'labelValuesToRows') {
                return (
                  <Col span={12} data-oid='h2d9:..'>
                    <Form.Item label={t('panel.custom.table.aggrDimension')} name={[...namePrefix, 'aggrDimension']} data-oid='n:or7:y'>
                      <Select mode='multiple' data-oid='zvva5um'>
                        {_.map(_.concat(calc === 'origin' ? '__time__' : [], tableFields), (item) => {
                          return (
                            <Select.Option key={item} value={item} data-oid='o8xtswv'>
                              {item}
                            </Select.Option>
                          );
                        })}
                      </Select>
                    </Form.Item>
                  </Col>
                );
              }
              return null;
            }}
          </Form.Item>
        </Row>
        <Row gutter={10} data-oid='1pve_g6'>
          <Col span={12} data-oid='8debcih'>
            <Form.Item noStyle shouldUpdate data-oid='ieucs3p'>
              {({ getFieldValue }) => {
                const displayMode = getFieldValue([...namePrefix, 'displayMode']);
                const fieldColumns = getFieldValue([...namePrefix, 'columns']);
                const columns = !_.isEmpty(fieldColumns) ? fieldColumns : _.concat(tableFields, 'value');
                let aggrDimension = getFieldValue([...namePrefix, 'aggrDimension']);
                aggrDimension = _.isArray(aggrDimension) ? aggrDimension : [aggrDimension];
                let keys: string[] = [];
                if (displayMode === 'seriesToRows') {
                  keys = ['name', 'value'];
                } else if (displayMode === 'labelsOfSeriesToRows') {
                  keys = columns;
                } else if (displayMode === 'labelValuesToRows') {
                  keys = _.concat(_.isEmpty(aggrDimension) ? ['name'] : aggrDimension, tableRefIds);
                }

                return (
                  <Form.Item label={t('panel.custom.table.sortColumn')} name={[...namePrefix, 'sortColumn']} data-oid='e6rg5gs'>
                    <Select
                      allowClear
                      onChange={() => {
                        if (!chartForm.getFieldValue([...namePrefix, 'sortOrder'])) {
                          const customValues = chartForm.getFieldValue('custom');
                          _.set(customValues, 'sortOrder', 'ascend');
                          chartForm.setFieldsValue({
                            custom: customValues,
                          });
                        }
                      }}
                      data-oid='o0srn-m'
                    >
                      {_.map(keys, (item) => {
                        return (
                          <Select.Option key={item} value={item} data-oid=':vuuxeu'>
                            {item}
                          </Select.Option>
                        );
                      })}
                    </Select>
                  </Form.Item>
                );
              }}
            </Form.Item>
          </Col>
          <Col span={12} data-oid='5-6:mxl'>
            <Form.Item label={t('panel.custom.table.sortOrder')} name={[...namePrefix, 'sortOrder']} data-oid='iu9-s6n'>
              <Select allowClear data-oid='zhy5sv9'>
                <Select.Option value='ascend' data-oid='hmcq3a:'>
                  Asc
                </Select.Option>
                <Select.Option value='descend' data-oid='svm.41s'>
                  Desc
                </Select.Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>
        <Form.Item label={t('panel.custom.table.link.mode')} name={[...namePrefix, 'linkMode']} initialValue='appendLinkColumn' data-oid='hdfrg23'>
          <Radio.Group buttonStyle='solid' data-oid='89hszir'>
            <Radio.Button value='appendLinkColumn' data-oid='93x.3me'>
              {t('panel.custom.table.link.appendLinkColumn')}
            </Radio.Button>
            <Radio.Button value='cellLink' data-oid='e7fhs5f'>
              {t('panel.custom.table.link.cellLink')}
            </Radio.Button>
          </Radio.Group>
        </Form.Item>
        <Form.Item
          label={
            <Space data-oid='gch8vjd'>
              {t('panel.base.link.label')}
              <Tooltip title={<Trans ns='dashboard' i18nKey='dashboard:var.help_tip' components={{ 1: <br data-oid='sn9l69s' /> }} data-oid='n14p12p' />} data-oid='u4njdas'>
                <InfoCircleOutlined data-oid='zdt2l1g' />
              </Tooltip>
            </Space>
          }
          style={{ marginBottom: 0 }}
          data-oid='ojhwhz0'
        >
          <Form.List name={[...namePrefix, 'links']} data-oid='acpg8a3'>
            {(fields, { add, remove }) => (
              <>
                <Button
                  style={{ width: '100%', marginBottom: 10 }}
                  onClick={() => {
                    add({});
                  }}
                  data-oid='_kteura'
                >
                  {t('panel.base.link.btn')}
                </Button>
                {fields.map(({ key, name, ...restField }) => {
                  return (
                    <Space
                      key={key}
                      style={{
                        alignItems: 'flex-start',
                      }}
                      data-oid='09sp8ga'
                    >
                      <Form.Item
                        {...restField}
                        name={[name, 'title']}
                        rules={[
                          {
                            required: true,
                            message: t('panel.base.link.name_msg'),
                          },
                        ]}
                        data-oid='n0tf7s.'
                      >
                        <Input placeholder={t('link.name')} data-oid='_ujspmp' />
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        name={[name, 'url']}
                        rules={[
                          {
                            required: true,
                            message: t('panel.base.link.url_msg'),
                          },
                        ]}
                        data-oid='7rw95_v'
                      >
                        <Input style={{ width: 284 }} placeholder={t('link.url')} data-oid='02-s0mg' />
                      </Form.Item>
                      <Tooltip title={t('panel.base.link.isNewBlank')} data-oid='tcpplwe'>
                        <Form.Item {...restField} name={[name, 'targetBlank']} valuePropName='checked' data-oid='g0k:3l4'>
                          <Switch data-oid='17io8e9' />
                        </Form.Item>
                      </Tooltip>
                      <Button
                        icon={<DeleteOutlined data-oid='pugs0y1' />}
                        onClick={() => {
                          remove(name);
                        }}
                        data-oid='7_u_.6t'
                      />
                    </Space>
                  );
                })}
              </>
            )}
          </Form.List>
        </Form.Item>
        <Form.Item label={t('panel.base.description')} name='description' data-oid='elvgefb'>
          <Mentions prefix='$' split='' rows={3} data-oid='bz9x5e:'>
            {_.map(variableConfigWithOptions, (item) => {
              return (
                <Mentions.Option key={item.name} value={item.name} data-oid='gln9cp2'>
                  {item.name}
                </Mentions.Option>
              );
            })}
          </Mentions>
        </Form.Item>
      </>
    </Panel>
  );
}
